/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.insta.browser.service.tab;

import fr.insta.browser.service.history.HistorySingleTabServiceFactory;
import fr.insta.browser.service.history.IHistorySingleTabService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>TabService class.</p>
 *
 * @author Maarek
 * @version $Id: $Id
 */
public class TabService implements ITabService {

    final private List<ChangeTabListener> listeners = new ArrayList<>();
    private Object currentTab;
    final private Map<Object, IHistorySingleTabService> historyServices = new HashMap<>();
    final private HistorySingleTabServiceFactory historySingleTabServiceFactory;

    /**
     * <p>Constructor for TabService.</p>
     *
     * @param historySingleTabServiceFactory a {@link fr.insta.browser.service.history.HistorySingleTabServiceFactory} object.
     */
    public TabService(HistorySingleTabServiceFactory historySingleTabServiceFactory) {
        this.historySingleTabServiceFactory = historySingleTabServiceFactory;
    }

    /** {@inheritDoc} */
    @Override
    public Object getCurrentTab() {
        return currentTab;
    }

    /** {@inheritDoc} */
    @Override
    public void setCurrentTab(Object currentTab) {
        Object oldTab = this.currentTab;
        this.currentTab = currentTab;
        fireChangeTab(oldTab, currentTab);
    }

    /** {@inheritDoc} */
    @Override
    public void addChangeTabListener(ChangeTabListener listener) {
        listeners.add(listener);
    }

    /** {@inheritDoc} */
    @Override
    public void removeChangeTabListener(ChangeTabListener listener) {
        listeners.remove(listener);
    }

    /**
     * <p>fireChangeTab.</p>
     *
     * @param oldTab a {@link java.lang.Object} object.
     * @param newTab a {@link java.lang.Object} object.
     */
    protected void fireChangeTab(Object oldTab, Object newTab) {
        for (ChangeTabListener listener : listeners) {
            listener.onChangeTab(this, oldTab, newTab);
        }
    }

    /** {@inheritDoc} */
    @Override
    public IHistorySingleTabService getCurrentHistoryService() {
        return getHistoryService(getCurrentTab());
    }

    /** {@inheritDoc} */
    @Override
    public IHistorySingleTabService getHistoryService(Object tab) {
        if (historyServices.get(tab) == null) {
            historyServices.put(tab, historySingleTabServiceFactory.create());
        }
        return historyServices.get(tab);
    }
}
